package cn.gary.oaserver.config.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: 邓必宏
 * @title:
 * @Demo:
 * @DateTime: 2024/3/18
 */
@Configuration
@EnableSwagger2 // 通过@EnableSwagger2注解来启用Swagger2
public class Swagger2Config {

    @Autowired
    JwtToken jwtToken;

    // Docket可以理解为API的正文
    @Bean
    public Docket createRestApi() { // 通过createRestApi()方法创建Docket的bean实例对象
        return new Docket( DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())//appInfo()用来创建Api的基本信息(这些信息会展示在Swagger文档页面中)
                .select()
                // 下面的包名为oa-server项目controller所在包
                .apis( RequestHandlerSelectors.basePackage("cn.gary.oaserver.controller"))
                .paths( PathSelectors.any())
                .build()
                .securitySchemes ( securitySchemes() )
                .securityContexts ( securityContexts() );
    }

    private List<SecurityContext> securityContexts() {
        List<SecurityContext> allContexts=new ArrayList<>();

        List<SecurityReference> securityReferences=new ArrayList<>();

        AuthorizationScope[] scopes={new AuthorizationScope ( "global","accessEverything" )};

        securityReferences.add ( new SecurityReference ( jwtToken.tokenHeader,scopes ) );

        allContexts.add(new SecurityContext ( securityReferences,PathSelectors.any () ));
        return allContexts;
    }

    private List<? extends SecurityScheme > securitySchemes() {
        List<ApiKey> apiKeys=new ArrayList<> (  );
        apiKeys.add ( new ApiKey(jwtToken.tokenHeader,jwtToken.tokenHeader,"Header") );
        return apiKeys;
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder ()
                .title("智能OA系统接口文档")
                .description("")
                .contact(new Contact ("czkt", "http://localhost:8081", "12345@qq.com"))
                .version("1.0")
                .build();
    }
}
